/*
 * Copyright 2019 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


import * as _ from "lodash"
import { PageList } from "../data"
import httpClient from "../httpclient"

export class BrowsingProduct {
  public id: string
  public name: string
  private image_url: string
  private store_id: string
  public follow_time: string

  public get imageUrl() {
    return this.image_url
  }

  public get storeId() {
    return this.store_id
  }

  public get followTime() {
    return this.follow_time
  }
}

export class BrowsingProductQuery {
  private params = {}
  private customer_id: string = ""

  public page(page: number) {
    this.params["page"] = page
    return this
  }

  public limit(limit: number) {
    this.params["limit"] = limit
    return this
  }

  public customerId(customerId: string) {
    this.customer_id = customerId
    return this
  }

  public list(): Promise<PageList<BrowsingProduct>> {
    return httpClient.get(`/v1/customers/${this.customer_id}/browsing-products`, { params: this.params })
      .then(({ data }) => {
        return _.assign(PageList.empty(), data, {
          elements: _.map(data.elements, element => _.assign(new BrowsingProduct(), element)),
        })
      })
  }
}

export class BrowsingProductServiceV1 {

  public static addBrowsingProduct(browserId: string, productId: string): Promise<BrowsingProduct> {
    return httpClient.post(`/v1/customers/${browserId}/browsing-products/${productId}`)
      .then(({ data }) => _.assign(new BrowsingProduct(), data))
  }

  public static getBrowsingProductCount(browserId: string): Promise<number> {
    return httpClient.get(`/v1/customers/${browserId}/browsing-products/count`)
      .then(({ data }) => data)
  }

  public static getBrowsingProducts(): BrowsingProductQuery {
    return new BrowsingProductQuery()
  }

  public static deleteBrowsingProduct(browserId: string, productId: string): Promise<void> {
    return httpClient.delete(`/v1/customers/${browserId}/browsing-products/${productId}`)
      .then(({ data }) => data)
  }
}
